package com.ruoyi.system.Utils;

import javax.usb.*;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class USBUtils {

//    static short VID = 0x339b;
//    static short PID = 0x107d;

    static short VID = 0x1a86;
    static short PID = 0x7523;

    public UsbDevice findDevice() throws UsbException {
        UsbHub hub = UsbHostManager.getUsbServices().getRootUsbHub();
        for (UsbDevice device : (List<UsbDevice>) hub.getAttachedUsbDevices())
        {
            UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
            if (desc.idVendor() == VID && desc.idProduct() == PID) return device;

        }
        return null;
    }


    // 初始化设备，请求获取、打开并接收数据
    public void initUseDevice(UsbDevice device) throws UsbException, UnsupportedEncodingException {
        List<UsbInterface> ifaces = device.getActiveUsbConfiguration().getUsbInterfaces();
        System.out.println("接口数量: "+ifaces.size());
//        for (UsbInterface usbInterface : ifaces) {
//            System.out.println("接口名称: "+usbInterface.getInterfaceString());
//            List<UsbEndpoint> endpoints = usbInterface.getUsbEndpoints();
//            for(UsbEndpoint endpoint : endpoints) {
//                System.out.println("Type: "+endpoint.getType()+" -Dir: "+endpoint.getDirection());
//            }
//        }
        UsbInterface usbInterface = ifaces.get(0);
        usbInterface.claim();
        UsbEndpoint endpoint = usbInterface.getUsbEndpoint((byte) 0x02);
        UsbPipe pipe = endpoint.getUsbPipe();
        pipe.open();
        int sent = pipe.syncSubmit(new byte[] {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x0A});
        System.out.println(sent + " bytes sent");
        pipe.close();
        usbInterface.release();

    }
}
